package com.boot2.core;

import com.boot2.core.utils.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.CollectionUtils;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @ClassName: BeanDefinitionSanner
 * @description: 定义好的bean的扫描器
 * @author zhangweilin
 * @date 2017年12月24日 上午10:15:54
 *
 */
public class BeanDefinitionSanner {

	private static String beanDefinitionClassCacheKey = "beanDefinitionClassCacheKey";
	private static Map<String, Map<String, String>> cacheMap = new HashMap<>();

	/**
	 * 获取指定注解所注解过的所有类，健值对，k:简单类名，首字母小写， v:类全名
	 * 
	 * @param basePackage
	 * @param annotationType
	 * @return
	 */
	public static Map<String, String> getBeanDefinition(String basePackage,
			Class<? extends Annotation> annotationType) {
		Map<String, String> map = null;
		map = cacheMap.get(annotationType.getSimpleName());
		if (!CollectionUtils.isEmpty(map)) {
			return map;
		}
		ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
		// provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
		// 查找注解了Table的所有类
		provider.addIncludeFilter(new AnnotationTypeFilter(annotationType));
		Set<BeanDefinition> beanDefinitionSet = provider.findCandidateComponents(basePackage);
		map = new HashMap<>(beanDefinitionSet.size());
		for (BeanDefinition component : beanDefinitionSet) {
			String className = component.getBeanClassName();
			String classSimpleName = StringUtils.changFirstWord(StringUtils.getLastSection(className, "."),
					StringUtils.toLowerCase);
			map.put(classSimpleName, className);
		}
		cacheMap.put(beanDefinitionClassCacheKey + "_" + annotationType.getSimpleName(), map);
		return map;
	}
}
